package com.javaweb.config.jasypt;

import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * jasypt加密配置
 * @author tank2140896
 */
@Configuration
public class JasyptConfig {
	
	/**
	 * jasypt加密配置
	 * <p>
	 * 自定义加密前后缀
	 * jasypt.encryptor.property.prefix=JavaWeb(
	 * jasypt.encryptor.property.suffix=)
	 * <p>
	 * var encryptor = new BasicTextEncryptor();
	 * encryptor.setPassword("JavaWeb");
	 * System.out.println(encryptor.encrypt("root"));
	 * System.out.println(encryptor.decrypt("XprGL8m3dVKV4/tIeNqvPkhIZx93Qg0gbXoUZGsiqen65Ry8l7OV79lAA3eFb2mk"));
	 * <p>
	 * System.out.println(new JasyptConfig().jasyptEncrypt().encrypt("root"));
	 * <p>
	 * 如果认为password写在配置类里还不安全，可以如下处理：
	 * java -jar JavaWeb.jar --jasypt.encryptor.password=JavaWeb
	 * java -Djasypt.encryptor.password=JavaWeb -jar JavaWeb.jar
	 * 配置系统环境变量如：JASYPT_PASSWORD=JavaWeb，然后配置文件写为：jasypt.encryptor.password=${JASYPT_PASSWORD:}
	 * <p>
	 * 关于password写在配置类里还不安全，可以有以下做法：1、jar包内混淆class文件；2、jar包代码与配置文件分离，可以在与jar包同级的位置下建个config文件夹，然后里面放个application.properties
	 * @return StringEncryptor StringEncryptor
	 */
	@Bean("jasyptEncrypt")
	@DependsOn("projectingArgumentResolverBeanPostProcessor")
    public StringEncryptor jasyptEncrypt() {
		var encryptor = new PooledPBEStringEncryptor();
		var config = new SimpleStringPBEConfig();
        config.setPassword("JavaWeb");
        config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }

}
